import { Drawer, DrawerProps } from 'antd'
import { ReactNode, useState } from 'react'

type UseDrawerProps = Omit<DrawerProps, 'open' | 'onClose' | 'loading'>

function useDrawer() {
  const [open, setOpen] = useState(false)
  const [drawerProps, setDrawerProps] = useState<UseDrawerProps>()
  const [content, setContent] = useState<ReactNode>()
  const [loading, setLoading] = useState<boolean>(false)

  function openDrawer(content: ReactNode, drawerProps?: UseDrawerProps) {
    setDrawerProps(drawerProps)
    if (content) setContent(content)
    setOpen(true)
  }

  function closeDrawer() {
    handleClose()
  }
  function handleClose() {
    setOpen(false)
  }

  const drawerContext: ReactNode = (
    <Drawer
      loading={loading}
      open={open}
      onClose={handleClose}
      destroyOnClose
      maskClosable={false}
      {...drawerProps}
    >
      {content}
    </Drawer>
  )

  return { openDrawer, closeDrawer, setLoading, setContent, drawerContext }
}

export default useDrawer
